<?php
namespace app\admin\model;
use think\Config;
use think\Db;
class CatModel extends \app\common\model\CommonModel
{
    
    /**
     * 新建分类
     * @param string $cat
     */
    public function addCat($cat)
    {
        try {
            $ret = Db::table('cat')->where(['cat' => $cat])->find();
            if($ret){
                throw new \Exception("分类已存在!");    
            }
            if(Db::table('cat')->insert(['cat' => $cat]) !== false){
                return true;
            }
            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 删除分类
     * @param int $catid
     */
    public function deleteCat($catid)
    {
        try {
            if(Db::table('tool')->where(['catid' => $catid])->find()){
                throw new \Exception("该分类下存在工具,不可删除!");    
            }
            if(Db::table('cat')->where(['id' => $catid])->delete()) return true;
            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 编辑分类
     * @param int    $catid
     * @param string $cat
     */
    public function editCat($catid,$cat)
    {
        try {
            if(Db::table('cat')->where("`id` != {$catid} AND `cat` = '{$cat}'")->find()){
                throw new \Exception("此分类已存在!");    
            }
            if(Db::table('cat')->where(['id' => $catid])->update(['cat' => $cat]) !== false) return true;
            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }    
    }

    /**
     * 分类列表
     */
    public function list()
    {
        try {
            $ret = Db::table('cat')->order('id desc')->select();
            foreach ($ret as $key => $value) {
                $ret[$key]['tool'] = Db::table('tool')->where(['catid' => $value['id']])->count();
            }
            return $ret;    
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }    
    }
}